package com.gitee.srurl.core.util.redis;

import com.gitee.srurl.core.exception.BloomNoExistException;
import com.gitee.srurl.core.util.SpringContextUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;

/**
 * @author zxw
 * @date 2023/4/29 20:14
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisBloomUtil {

    private static final RedissonClient redissonClient = SpringContextUtil.getBean(RedissonClient.class);

    public static boolean add(String key, String value) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(key);
        return bloomFilter.add(value);
    }

    public static boolean contains(String key, String value) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(key);
        boolean exists = bloomFilter.isExists();
        if (!exists) {
            log.error("布隆过滤器:{},不存在", key);
            throw new BloomNoExistException();
        }
        return bloomFilter.contains(value);
    }

    public static void initBloom(String key, long expectedInsertions, double fpp) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(key);
        if (bloomFilter.isExists()) {
            log.info("bloom:{},existed,init skip", key);
        }
        bloomFilter.tryInit(expectedInsertions, fpp);
    }

    public static boolean bloomExists(String key) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(key);
        return bloomFilter.isExists();
    }
}
